<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package    FeatherPHP
 * @subpackage ACL
 * @copyright  Copyright (c) 2006, Julien PORTALIER
 * @link       http://portalier.com/feather
 * @license    http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class ArosAco extends Model
{
	public    $belongsTo   = array('Aro','Aco');
	protected $cachedRoles = array();
	
	function & resolveIDs($aco, $aro=null)
	{
		$this->conditions(array('Aco.aco' => $aco));
		if (!empty($aro))
			$this->conditions(array('Aro.aro' => $aro));
		
		$this->process = Q_PROCESS_LIST;
		$rs = $this->findAll('ArosAco.id');
		return $rs;
	}
	
	function & fetchRoles($conditions)
	{
		// cached in memory?
		$_md5 = md5(print_r($conditions, true));
		if (isset($this->cachedRoles[$_md5])) {
			return $this->cachedRoles[$_md5];
		}
		else
		{
			// cached on disk?
			$fname = 'perms'.DS.$_md5;
			$cache = (DEBUG != 2) ? cache($fname, null, '+30 minutes') : null;
			
			if (!empty($cache)) {
				$roles = unserialize($cache);
			}
			else
			{
				// not cached: fetching
				$roles = array();
				$this->conditions(&$conditions);
				$perms = $this->findAll('Aro.aro, ArosAco.read, ArosAco.write, ArosAco.delete');
				
				if (!empty($perms))
				{
					foreach ($perms as $p)
						$roles[$p['Aro']['aro']] =& $p['ArosAco'];
				}
				
				// caching: disk & memory
				cache($fname, serialize($roles));
				$this->cachedRoles[$_md5] =& $roles;
			}
			return $roles;
		}
	}
	
	// admin
	
	function create($aro, $aco, $read=null, $write=null, $delete=null)
	{
		$rs = $this->resolveIDs($aco, $aro);
		$data = array();
		if (!is_null($read))   $data['read']   = $read;
		if (!is_null($write))  $data['write']  = $write;
		if (!is_null($delete)) $data['delete'] = $delete;
		
		if (!empty($rs))
		{
			$this->id = $rs[0];
			$this->saveFields(&$data);
		}
		else
		{
			$data['aro_id'] = $this->Aro->resolveID($aro);
			$data['aco_id'] = $this->Aco->resolveID($aco);
			
			if (empty($data['aco_id']))
				$data['aco_id'] = $this->Aco->create($aco);
			
			$this->__setData(&$data);
			$this->__save('insert');
		}
		
		return $this->id;
	}
	
	function destroy($aco, $aro=null)
	{
		$rs = $this->resolveIDs($aco, $aro);
		if (!empty($rs))
		{
			$this->conditions(array('id' => &$rs));
			$this->operator('OR');
			return $this->__delete();
		}
		return true;
	}
	
	// overrides
	
	protected function __get($name)
	{
		$this->$name = new $name;
		return $this->$name;
	}
}
?>